import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';

import localCache from '@/utils/cache';
import { firstMenu } from '@/utils/map-menu';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('../views/main/main.vue')
    // children -> 根据userMenu来决定
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/login.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('../views/not-found/not-found.vue')
  }
];

const router = createRouter({
  routes,
  history: createWebHistory()
});

// 导航守卫

router.beforeEach((to) => {
  // 在没有登录时,返回到login页面
  if (to.path !== '/login') {
    const token = localCache.getCache('token');
    if (!token) {
      return '/login';
    }
  }

  // 进入main页面，添加上二级菜单的path
  if (to.path === '/main') {
    return firstMenu.url;
  }
});

export default router;
